#include "LoggerImpl.h"
#include <QtCore/QDebug>

Logger::Logger(const QString& path) 
: _fullpath(path + "/log/")
, _detailLevel(CRITICAL)
{}

void Logger::setPath(const QString& path)
{	
	QDir().mkpath(_fullpath = path + "/log/");
    open();	
}

void Logger::setDetailLevel(int detailLevel)
{
	_detailLevel = detailLevel & DETAIL_MASK | CRITICAL;
}

void Logger::open()
{
    _file.close();
	QDate current_date = QDate::currentDate();
	_day = current_date.day();
    
	_file.setFileName(_fullpath + QString("%1.log").arg(_day));
    _file.open(QIODevice::ReadWrite | QIODevice::Text);

    bool sameMonth = current_date.month() == QFileInfo(_file).lastModified().date().month();
    _file.seek(sameMonth ? _file.size() : 0);
}

void Logger::check_day()
{
	if (_day != QDate::currentDate().day()) open();
}

void Logger::add(const QString& str, char detailLevel)
{
    QMutexLocker locker(&_mutex);

	if (_detailLevel & (detailLevel & DETAIL_MASK))
	{
		check_day();

		QString head = "[" + QTime::currentTime().toString("hh:mm:ss") + "] "; 

		_file.write(head.toLocal8Bit());
		_file.write(str .toLocal8Bit());
        _file.flush();
	}
}

void Logger::addn(const QString& str, char detaiLevel)
{
    add(str + "\n", detaiLevel);
}